/*
 * Copyright Eduardo Aponte 2013
 * aponteeduardo@gmail.com
 */
#include <eyelink.h>
#include <string.h>
#include "mex.h"


INT16 _main( ELINKADDR node, char FARTYPE *msg )
{
    return eyelink_node_send_message( node, msg );
}

void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] )
{
    mwSize td[2] = {1,1};
    double *status;
    char FARTYPE *msg;
    char *addr;
    ELINKADDR eladdr;
    int i;

    /* Verify input arguments. */
    if(nrhs != 2 ) {
        mexErrMsgTxt("Incorrect number of inputs.");
    } else if( nlhs > 1 ) {
        mexErrMsgTxt("Too many output arguments.");
    }
    
    if (!mxIsChar(prhs[0]))
        mexErrMsgTxt("node should be a string.");
       
    if (!mxIsChar(prhs[1]))
        mexErrMsgTxt("msg should be a string.");
     
    addr = mxArrayToString(prhs[0]);

    if ( addr == NULL )
	mexErrMsgTxt("addr could not be read.");
	

    if ( strlen(addr) != ELINKADDRSIZE ){
	mxFree( addr );
	mexErrMsgTxt("node should be a string of len ELINKADDRSIZE (16).");
    }

    msg = mxArrayToString(prhs[1]);
	
    if ( msg == NULL ){
	mxFree( addr );
	mxErrMsgTxt("msg could not be read");
    }
   
    for (i = 0; i < ELINKADDRSIZE; i++)
        eladdr[i] = (byte ) addr[i];
       
    plhs[0] = mxCreateNumericArray( 2, td, mxDOUBLE_CLASS, mxREAL);
    status = mxGetPr(plhs[0]);
    
    *status = (double ) _main( eladdr, msg );

    mxFree( addr );
    mxFree( msg );

    return;
}
